package com.scedu.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.scedu.springcloud.handler.CustomerBlockHandler;
import com.scedu.springcloud.springcloud.entity.CommonResult;
import com.sun.deploy.security.SelectableSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.IllegalFormatException;

@RestController
class OrderController {
    @Autowired
    private RestTemplate restTemplate;
    @Value("${server.port}")
    private String port;
    public  static  final  String PAYMENT_URL="http://naco-payment-provider";

    @RequestMapping(value = "/consumer/get/{id}", method = RequestMethod.GET)
    @SentinelResource(value = "get",
            blockHandlerClass =CustomerBlockHandler.class, //自定义限流处理类
            blockHandler = "handlerException1",
            fallbackClass =CustomerBlockHandler.class, //自定义限流处理类
            fallback = "fallbackException1")  //自定义限流处理类中的方法
    public CommonResult get(@PathVariable Long id) {
        CommonResult result = restTemplate.getForObject(PAYMENT_URL+"/paymentSQL/" + id, CommonResult.class);
        if (id==4) {
            throw new IllegalArgumentException("非法参数");
            }
            else if (result.getData()==null){
            throw new NullPointerException("空数据异常");
        }

        return new CommonResult(200,"from order data is "+port,result);

    }

    @RequestMapping(value = "/consumer/getEntity/{id}", method = RequestMethod.GET)
//    @SentinelResource(value = "getEntity",
//            fallbackClass =CustomerBlockHandler.class, //自定义限流处理类
//            fallback = "fallbackException1")
    @SentinelResource(value = "getEntity",
            blockHandlerClass =CustomerBlockHandler.class, //自定义限流处理类
            blockHandler = "handlerException1")
    public CommonResult getEntity(@PathVariable Long id) {
        ResponseEntity<CommonResult> forEntity = restTemplate.getForEntity(PAYMENT_URL + "/paymentSQL/" + id, CommonResult.class);
        if (id==4) {
            throw new IllegalArgumentException("非法参数");
        }
        else if (forEntity.getBody()==null){
            throw new NullPointerException("空数据异常");
        }
        return new CommonResult(200,"from order data is "+port,forEntity.getBody());

    }
}
